const plugin = requirePlugin("WechatSI")

// 获取**全局唯一**的语音识别管理器**recordRecoManager**
const manager = plugin.getRecordRecognitionManager()

const db = wx.cloud.database()
Page({
  data: {
    title: '',
    text: '',
    text_old: '',
    bottomButtonDisabled: false, // 底部按钮disabled
    recording: false,  // 正在录音
    recordStatus: 0,   // 状态： 0 - 录音中 1- 翻译中 2 - 翻译完成/二次翻译
    id: ''
  },

  //表单提交事件，有id责修改数据，否则添加数据
  formSubmit: function (e) {
    if (this.data.id) {
      db.collection('note').doc(this.data.id).update({
        data: {
          title: e.detail.value.title,
          text: e.detail.value.text,
          type: 2,
          create_time: new Date()
        }
      }).then(res => {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.switchTab({
            url: '../index/index'
          })
        }, 2000)
      }).catch(console.error)
    } else {
      db.collection('note').add({
        data: {
          title: e.detail.value.title,
          text: e.detail.value.text,
          type: 2,
          create_time: new Date()
        }
      }).then(res => {
        this.setData({
          id: res._id
        })
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.switchTab({
            url: '../index/index'
          })
        }, 2000)
      }).catch(console.error)
    }
  },

  /**
   * 按住按钮开始语音识别
   */
  streamRecord: function (e) {
    wx.vibrateShort({
      complete: (res) => {},
    })
    // console.log("streamrecord" ,e)
    let detail = e.detail || {}
    let buttonItem = detail.buttonItem || {}
    manager.start({
      lang: buttonItem.lang,
    })

    this.setData({
      text_old: this.data.text,
      recordStatus: 0,
      recording: true
    })

  },
  textareaAInput(e) {
    this.setData({
      text: e.detail.value
    })
  },

  /**
   * 松开按钮结束语音识别
   */
  streamRecordEnd: function (e) {

    // console.log("streamRecordEnd" ,e)
    let detail = e.detail || {}  // 自定义组件触发事件时提供的detail对象
    let buttonItem = detail.buttonItem || {}

    // 防止重复触发stop函数
    if (!this.data.recording || this.data.recordStatus != 0) {
      console.warn("has finished!")
      return
    }

    manager.stop()

    this.setData({
      bottomButtonDisabled: true,
    })
  },




  /**
   * 识别内容为空时的反馈
   */
  showRecordEmptyTip: function () {
    this.setData({
      recording: false,
      bottomButtonDisabled: false,
    })
    wx.showToast({
      title: "请说话",
      icon: 'success',
      image: '/images/no_voice.png',
      duration: 1000,
      success: function (res) {

      },
      fail: function (res) {
        console.log(res);
      }
    });
  },


  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function () {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      this.setData({
        text: this.data.text_old + res.result
      })
    }

    // 识别结束事件
    manager.onStop = (res) => {

      let text = res.result

      if (text == '') {
        this.showRecordEmptyTip()
        return
      }
      this.setData({
        recordStatus: 1,
        bottomButtonDisabled: false,
        recording: false,
      })
    }

    // 识别错误事件
    manager.onError = (res) => {

      this.setData({
        recording: false,
        bottomButtonDisabled: false,
      })

    }
  },

  onShow: function () {

  },

  onLoad: function (e) {
    if (e.id) {
      this.setData({
        id: e.id
      })
      this.getNote()
    }
    this.initRecord()
    this.getRecordAuth()
  },

  // 获取note集合数据，并渲染
  getNote: function () {
    db.collection('note').doc(this.data.id).get().then(res => {
      this.setData({
        title: res.data.title,
        text: res.data.text
      })
    })
  },
  
  // 权限询问
  getRecordAuth: function () {
    wx.getSetting({
      success(res) {
        console.log("succ")
        console.log(res)
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              console.log("succ auth")
            }, fail() {
              console.log("fail auth")
            }
          })
        } else {
          console.log("record has been authed")
        }
      }, fail(res) {
        console.log("fail")
        console.log(res)
      }
    })
  }
})
